﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Excel;
namespace BYManageInfoSystem
{
    public partial class Frm_FeeMonthBYShouJuDetail : Form
    {
        private DGBY.BLL.FacFeeTab m_bllFacFeeTab = new DGBY.BLL.FacFeeTab();
        private DGBY.BLL.FeeTrueRecvRegPrivateTab m_bllFeeTrueRecvRegPrivateTab = new DGBY.BLL.FeeTrueRecvRegPrivateTab();
        private DGBY.BLL.FeeInvoiceTab m_bllFeeInvoiceTab = new DGBY.BLL.FeeInvoiceTab();
        private int m_nSelectFeeTTLoanTabID = 0;
        public class CustomMergedCellEvaluator : Infragistics.Win.UltraWinGrid.IMergedCellEvaluator
        {
            UltraGridColumn m_BaseColumn = null;
            public CustomMergedCellEvaluator(UltraGrid UltraGridTemp)
            {
                foreach (UltraGridColumn column2 in UltraGridTemp.DisplayLayout.Bands[0].Columns)
                {
                    string str = column2.Header.Caption;
                    if (str == "所属部门")
                    {
                        m_BaseColumn = column2;
                        break;
                    }
                }
            }
            // 合并日期相同的单元格（无需时间精确相同）
            public bool ShouldCellsBeMerged(UltraGridRow row1, UltraGridRow row2, UltraGridColumn column)
            {
                string str1 = (string)row1.GetCellValue(m_BaseColumn);
                string str2 = (string)row2.GetCellValue(m_BaseColumn);

                return str1 == str2;

            }

        }

        public Frm_FeeMonthBYShouJuDetail()
        {
            InitializeComponent();
        }
        public void LocalPrintPreveiw()
        {
            Infragistics.Shared.ResourceCustomizer rc = Infragistics.Win.Printing.Resources.Customizer;//Resources.Customizer;
            rc.SetCustomizedString("PrintPreview_DialogCaption", "打印预览");
            rc.SetCustomizedString("PrintPreview_Tool_Print", "打印(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_ClosePreview", "关闭(&C)");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuPreviewZoom", "显示比例");
            rc.SetCustomizedString("PrintPreview_Tool_Current_Page", "当前页");
            rc.SetCustomizedString("PrintPreview_Tool_Exit", "退出(&X)");
            rc.SetCustomizedString("PrintPreview_Tool_First_Page", "第一页");
            rc.SetCustomizedString("PrintPreview_Tool_Go_To", "跳至");
            rc.SetCustomizedString("PrintPreview_Tool_Last_Page", "最后一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_Page", "下一页");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_Page", "前一页");
            rc.SetCustomizedString("PrintPreview_Tool_Next_View", "下一视图(&N)");
            rc.SetCustomizedString("PrintPreview_Tool_Previous_View", "前一视图(&P)");
            rc.SetCustomizedString("PrintPreview_Tool_Hand_Tool", "手型工具(&H)");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Setup", "页面设置(&U)");
            rc.SetCustomizedString("PrintPreview_Tool_Snapshot_Tool", "快照工具(&S)");
            rc.SetCustomizedString("PrintPreview_Tool_View", "视图(&V)");
            rc.SetCustomizedString("PrintPreview_Tool_Whole_Page", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom", "缩放(&Z)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In", "放大");

            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out", "缩小");

            rc.SetCustomizedString("PrintPreview_ToolCategory_Context_Menus", "上下文菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_File", "文件");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Menus", "菜单");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Tools", "工具栏");
            rc.SetCustomizedString("PrintPreview_ToolCategory_View", "视图");
            rc.SetCustomizedString("PrintPreview_ToolCategory_Zoom_Mode", "缩放模式");

            rc.SetCustomizedString("PrintPreview_ToolTip_ClosePreview", "关闭");
            rc.SetCustomizedString("PrintPreview_ToolTip_Zoom", "缩放");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "页:{0}/{1}");

            rc.SetCustomizedString("CustomizeImg_ToolBar_MenuBar", "菜单");
            rc.SetCustomizedString("CustomizeImg_ToolBar_Standard", "标准");
            rc.SetCustomizedString("CustomizeImg_ToolBar_View", "视图");
            rc.SetCustomizedString("PrintPreview_Tool_File", "文件(&F)");
            rc.SetCustomizedString("PrintPreview_Tool_Tools", "工具(&T)");
            rc.SetCustomizedString("PrintPreview_Tool_Dynamic_Zoom_Tool", "动态缩放工具(&D)");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_Out_Tool", "缩小工具");
            rc.SetCustomizedString("PrintPreview_Tool_Zoom_In_Tool", "放大工具");
            // rc.SetCustomizedString("PrintPreview_Tool_Page_Layout","菜单");
            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PreviewRowColSelection_SelectedPages", "{0} x {1} 页");

            rc.SetCustomizedString("PreviewRowColSelection_Cancel", "取消");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Width", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_MarginWidth", "文字宽度");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_PageWidth", "页宽");
            rc.SetCustomizedString("PrintPreview_ZoomListItem_WholePage", "合适页");
            rc.SetCustomizedString("PrintPreview_Tool_Page_Layout", "页面布局");
            rc.SetCustomizedString("PrintPreview_Tool_Margin_Width", "文字宽度");
            rc.SetCustomizedString("ContextMenuPreviewHand", "缩放视图");


            rc.SetCustomizedString("PrintPreview_Tool_Reduce_Page_Thumbnails", "缩小");
            rc.SetCustomizedString("PrintPreview_Tool_Show_Page_Numbers", "显示页号");
            rc.SetCustomizedString("PrintPreview_Tool_ContextMenuThumbnail", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Enlarge_Page_Thumbnails", "放大");
            rc.SetCustomizedString("PrintPreview_Tool_Thumbnails", "缩略图");
            rc.SetCustomizedString("PrintPreview_Tool_Continuous", "连续排序");
            //说明
            rc.SetCustomizedString("StatusBar_DynamicZoom_Instructions", "单击并拖动进行缩放操作");
            rc.SetCustomizedString("StatusBar_Page_X_OF_X", "当前页: {0} / {1}");
            rc.SetCustomizedString("StatusBar_SnapShot_Instructions", "单击并拖动,系统将选定矩型区域复制到剪帖板");
            rc.SetCustomizedString("StatusBar_ZoomIn_Instructions", "单击并拖动,系统将放大选定矩型区域");
            rc.SetCustomizedString("StatusBar_ZoomOut_Instructions", "单击并拖动,系统将缩小选定矩型区域");
            rc.SetCustomizedString("StatusBar_Hand_Instructions", "单击并拖动以便显示更多内容");
        }
        /// 取得某月的第一天
        /// </summary>
        /// <param name="datetime">要取得月份第一天的时间</param>
        /// <returns></returns>
        private DateTime FirstDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day);
        }
        /// <summary>
        /// 取得某月的最后一天
        /// </summary>
        /// <param name="datetime">要取得月份最后一天的时间</param>
        /// <returns></returns>
        private DateTime LastDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
        }

        private void ShowAllRecordInDataGridView()
        {
            DateTime dtFirst = FirstDayOfMonth(this.dateTimePickerDate.Value);
            DateTime dtEnd = LastDayOfMonth(this.dateTimePickerDate.Value);
            DataSet ds = m_bllFacFeeTab.ShowBYShouJuDetailRec("FeeInvoiceTab.TrueInvoiceJinE > 0"
                                + " and BGDComeBackTab.SBDate >= '" + dtFirst.Date + "'"
                                + " and BGDComeBackTab.SBDate <= '" + dtEnd.Date + "'"
                                + " and BYFeeKaiPiaoCateTab.BYFeeKaiPiaoCateName like " + "'%" + "百业收据" + "%'");

            if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                ds.Tables[0].Columns.Add("私帐收款", System.Type.GetType("System.Decimal"));
                ds.Tables[0].Columns["私帐收款"].SetOrdinal(7);
                ds.Tables[0].Columns.Add("合计", System.Type.GetType("System.Decimal"));
                ds.Tables[0].Columns["合计"].SetOrdinal(8);


                Dictionary<string, Decimal> dep2TotalJinE = new Dictionary<string, decimal>();

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string strTemp = ds.Tables[0].Rows[i]["工厂名称"].ToString();
                    DataSet ds2 = m_bllFeeTrueRecvRegPrivateTab.GetAllNotLogisticsTruePayRegList("FactoryDataTab.FactoryName = '" + strTemp + "'"
                                                                                                    + " and ShenBaoDate >= '" + dtFirst.Date + "'"
                                                                                                     + " and ShenBaoDate <= '" + dtEnd.Date + "'");

                    if (ds2.Tables.Count > 0 && ds2.Tables[0].Rows.Count > 0)
                    {
                        ds.Tables[0].Rows[i]["私帐收款"] = ds2.Tables[0].Rows[0]["百业收据实收费用"];
                    }
                    else
                    {
                        ds.Tables[0].Rows[i]["私帐收款"] = 0;
                    }

                    Decimal dtTemp = (Decimal)ds.Tables[0].Rows[i]["私帐收款"];

                    string strDep = ds.Tables[0].Rows[i]["所属部门"].ToString();
                    if (dep2TotalJinE.Keys.Contains(strDep))
                        dep2TotalJinE[strDep] += dtTemp;
                    else
                        dep2TotalJinE.Add(strDep, dtTemp);
                }


                DataTable dtNew = null;
                dtNew = ds.Tables[0].Clone();
                Decimal dtTotal = 0;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    string strTemp = ds.Tables[0].Rows[i]["工厂名称"].ToString();
                    DataSet ds2 = m_bllFeeTrueRecvRegPrivateTab.GetAllNotLogisticsTruePayRegList("FactoryDataTab.FactoryName = '" + strTemp + "'"
                                                                                                    + " and ShenBaoDate >= '" + dtFirst.Date + "'"
                                                                                                     + " and ShenBaoDate <= '" + dtEnd.Date + "'");

                    if (ds2.Tables.Count > 0 && ds2.Tables[0].Rows.Count > 0)
                    {
                        ds.Tables[0].Rows[i]["私帐收款"] = ds2.Tables[0].Rows[0]["百业收据实收费用"];
                    }
                    else
                    {
                        ds.Tables[0].Rows[i]["私帐收款"] = 0;
                    }
                    string strDep = ds.Tables[0].Rows[i]["所属部门"].ToString();
                    ds.Tables[0].Rows[i]["合计"] = dep2TotalJinE[strDep];
                    dtNew.Rows.Add(ds.Tables[0].Rows[i].ItemArray);

                    Decimal dtTemp = Convert.ToDecimal(ds.Tables[0].Rows[i]["实际票面金额"].ToString());
                    dtTotal += dtTemp;
                }

                DataRow dr = dtNew.NewRow();
                dr["工厂名称"] = "合计";
                dr["实际票面金额"] = dtTotal;
                dr["所属部门"] = "";
                dtNew.Rows.Add(dr);

                if (dtNew.Rows.Count > 0)
                {
                    ultraGrid1.DataSource = dtNew;
                    ultraGrid1.DisplayLayout.Bands[0].Columns[0].Hidden = true;
                    ultraGrid1.DisplayLayout.Bands[0].Columns[1].Hidden = true;
                }
            }
            

        }
        private void buttonImport_Click(object sender, EventArgs e)
        {
            ShowAllRecordInDataGridView();
        }

        private void buttonExportToExcel_Click(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)ultraGrid1.DataSource;

            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel文件(*.xls)|*.xls";
                    string outFile = "";

                    if (sfd.ShowDialog() == DialogResult.OK)
                    {
                        outFile = sfd.FileName;
                    }
                    else
                    {
                        return;
                    }

                    ultraGridExcelExporter1.Export(ultraGrid1, outFile);
                }
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            this.ultraGridPrintDocument1.Grid = this.ultraGrid1;
            this.ultraPrintPreviewDialog1.Document = this.ultraGridPrintDocument1;
            this.ultraPrintPreviewDialog1.ShowDialog(this);
        }

        private void ultraGrid1_AfterCellActivate(object sender, EventArgs e)
        {
            string strTemp = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells[2].Text;
            if (strTemp == "合计")
                return;
            string strFeeTTLoanTabID = this.ultraGrid1.Rows[this.ultraGrid1.ActiveCell.Row.Index].Cells[1].Text;
            m_nSelectFeeTTLoanTabID = Convert.ToInt32(strFeeTTLoanTabID, 10);
            cellFeeTTLoanTabClick();
        }
        private void cellFeeTTLoanTabClick()
        {
            DGBY.Model.FeeInvoiceTab modelFeeInvoiceTab = m_bllFeeInvoiceTab.GetModel(m_nSelectFeeTTLoanTabID);
            if (modelFeeInvoiceTab != null)
            {
                this.textBoxFeeCate.Text = modelFeeInvoiceTab.InvoiceNo;
                this.dateTimePickerKaiPiao.Value = (System.DateTime)modelFeeInvoiceTab.InvoiceDate;

            }
        }

        private void buttonModify_Click(object sender, EventArgs e)
        {
            try
            {
                DGBY.Model.FeeInvoiceTab modelFeeInvoiceTab = m_bllFeeInvoiceTab.GetModel(m_nSelectFeeTTLoanTabID);
                if (modelFeeInvoiceTab == null)
                {
                    MessageBox.Show("数据库不存在该记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                modelFeeInvoiceTab.InvoiceNo = this.textBoxFeeCate.Text;
                modelFeeInvoiceTab.InvoiceDate = this.dateTimePickerKaiPiao.Value;
                m_bllFeeInvoiceTab.Update(modelFeeInvoiceTab);
                ShowAllRecordInDataGridView();
                MessageBox.Show("数据修改成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
        

        }

        private void ultraGrid1_InitializeRow(object sender, Infragistics.Win.UltraWinGrid.InitializeRowEventArgs e)
        {
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.CellAppearance.TextVAlign = VAlign.Middle;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextHAlign = HAlign.Center;
            ultraGrid1.DisplayLayout.Override.MergedCellAppearance.TextVAlign = VAlign.Middle;

            ultraGrid1.DisplayLayout.Bands[0].Columns["合计"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["所属部门"].MergedCellStyle = MergedCellStyle.Always;
            ultraGrid1.DisplayLayout.Bands[0].Columns["合计"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
            ultraGrid1.DisplayLayout.Bands[0].Columns["所属部门"].MergedCellEvaluator = new
   CustomMergedCellEvaluator(this.ultraGrid1);
        }

        private void ultraGridExcelExporter1_BeginExport(object sender, Infragistics.Win.UltraWinGrid.ExcelExport.BeginExportEventArgs e)
        {
            Worksheet ws = e.CurrentWorksheet;
            ws.Rows[1].Cells[3].CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Center;
            ws.Rows[2].Cells[0].CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Center;
            DateTime dtFirst = FirstDayOfMonth(this.dateTimePickerDate.Value);
            string strYear = dtFirst.Year.ToString();
            string strMonth = dtFirst.Month.ToString();
            ws.Rows[1].Cells[3].Value = strYear + "年" + strMonth + "月" + "百业收据明细"; 
            ws.Rows[2].Cells[0].Value = @"摘要：收到XXX" + strYear + "年" + strMonth + "月" + "费用"; 
            e.CurrentRowIndex = 3;
        }
    }
}
